
import { UI_Layer } from '../../config/ui_def'
import { WX_AD_CONFIG, Sdk_Platform, VIVO_AD_CONFIG, OPPO_AD_CONFIG } from '../../frame/constants';
import { GACHATIME, GACHATIMEGRP, GACHALEVEL } from '../../config/play_def'
import gacha from '../tool/gacha';
import util from '../tool/util';
cc.Class({
    extends: cc.Component,

    properties: {
        title_lab: cc.Label,
        content: cc.Node,
        starNode: cc.Node,

        go_status: false,           // 前往下一关状态
        top_node: cc.Node,
        bottom_node: cc.Node,
        start_button: cc.Button,
        gacha_btn: cc.Button,
        time_lab: cc.Label,
        cantClick: cc.Node,
        frame_sp: cc.Sprite,
        bgSkeleton: sp.Skeleton,
        realBigBgSpine: sp.Skeleton,
        bossSpine: sp.Skeleton,
        boxContent: cc.Node,
    },


    initPage() {
        if (!he.pool.getPool('scrollAd')) {
            he.pool.createPoolSync('scrollAd', 5, cc.Prefab, 'uimod/scrollAd')
        }
        if (!he.pool.getPool('adIcon')) {
            he.pool.createPoolSync('adIcon', 5, cc.Prefab, 'uimod/adIcon')
        }
        // if (!he.pool.getPool('boxItem')) {
        //     he.pool.createPoolSync('boxItem', 5, cc.Prefab, 'uimod/boxItem')
        // }
        let boxNum = 15 - this.boxContent.childrenCount
        let boxitem = he.load.get("uimod/boxItem")
        for (let k = 0; k < boxNum; k++) {
            let pre = cc.instantiate(boxitem)
            this.boxContent.addChild(pre)
        }
        let addNum = 5 - this.content.childrenCount
        let reward_prefab = he.load.get("uimod/bagItem")
        for (let i = 0; i < addNum; i++) {
            let reward_node = cc.instantiate(reward_prefab)
            this.content.addChild(reward_node)
        }
        for (let j = 0; j < this.content.children.length; j++) {
            if (j == 0) {
                this.content.children[j].setScale(0.7)
            }
            if (j == 1) {
                this.content.children[j].setScale(0.65)
                this.content.children[j].y = 4
            }
            if (j == 2) {
                this.content.children[j].setScale(0.6)
                this.content.children[j].y = 7
            }
            if (j == 3) {
                this.content.children[j].setScale(0.55)
                this.content.children[j].y = 13
            }
            if (j == 4) {
                this.content.children[j].setScale(0.5)
                this.content.children[j].y = 17
            }
        }
        this.loadPlayBundle()

    },
    updatePage(param) {
        if (param.passId) {
            this.pageInit(param.passId)
            let pass = he.db.getDataByArgs('Pass', { id: param.passId })
            gg.data.pass_id = pass.id
            this.mainPass = pass.main_pass
        } else {
            let passList = he.local.getJson('pass_list', 'user')
            if (passList && passList.length > 0) {
                let pass = he.db.getDataByArgs('Pass', { order: (passList.length + 1) })
                //     // console.log(pass)
                gg.data.pass_id = pass.id
                this.mainPass = pass.main_pass
            } else {
                gg.data.pass_id = 10101
                this.mainPass = 1
            }
            this.pageInit(gg.data.pass_id)
        }
        this.bottom_left = this.bottom_node.getChildByName('left')
        this.bottom_right = this.bottom_node.getChildByName('right')
        let dida = he.local.get('local_dida')
        if (!dida) {
            this.dida = 0
        } else {
            this.dida = parseInt(dida)
        }
        this.showNone = false
        this.canClick = true
        // this.bgSkeleton.setAnimation(0, 'stand_by', true)
        this.closeUI()
        // this.boxsInit()
        gg.eventManager.on('timeCheck', this.updateChargeStatus, this)
        this.updateChargeStatus()
        this.adSwitch(true)
        let passTable = he.db.getTable('Monster')
        let bossGrp = []
        for (let j = 0; j < passTable.length; j++) {
            if (passTable[j].rank == 5) {
                bossGrp.push(passTable[j].model)
            }
        }
        this.realBigBgSpine.addAnimation(0, 'stand_by', true)
        this.bossSpine.defaultSkin = bossGrp[this.mainPass - 1]
        this.bossSpine.setSkin(bossGrp[this.mainPass - 1])
    },



    checkTime() {

    },



    // 加载战斗包
    loadPlayBundle() {
        this.bundle_list = []
        this.start_button.interactable = false
        for (let i = 0; i < common.play_bundle_list.length; i++) {
            he.load.loadBundle(common.play_bundle_list[i], this.checkBundle.bind(this))
        }
    },
    // 检查战斗包
    checkBundle(error, res) {
        if (res && res.name) {
            this.bundle_list.push(res.name)
            if (common.play_bundle_list.length == this.bundle_list.length) {
                this.start_button.interactable = true
                // 测试
                // this.test()
            }
        }
    },
    // 测试
    test() {
        gg.data.goPass(10710)
        cc.director.loadScene("Playground");
    },

    adSwitch(status) {
        if (status) {
            switch (common.sdk_env) {
                case Sdk_Platform.WECHAT:
                    if (!common.showAd) return
                    he.ad.getTdAdJson(WX_AD_CONFIG.tmIcon[1], this.topSet.bind(this))
                    he.ad.getTdAdJson(WX_AD_CONFIG.tmIcon[2], this.bottomSet.bind(this))
                    // he.ad.interstitialShow()
                    break
            }
        } else {
            //  关掉广告
        }
    },
    closeUI() {
        for (let i = (this.top_node.children.length); i > 0; i--) {
            this.top_node.children[i - 1].getComponent('scrollAd').clearItem()
            he.pool.putElement('scrollAd', this.top_node.children[i - 1])
        }

        // for (let j = (this.boxContent.children.length); j > 0; j--) {
        //     he.pool.putElement('boxItem', this.boxContent.children[j - 1])
        // }

        if (this.bottom_left.children[0]) {
            this.bottom_left.children[0].getComponent('adIcon').clear()
            he.pool.putElement('adIcon', this.bottom_left.children[0])
        }

        if (this.bottom_right.children[0]) {
            this.bottom_right.children[0].getComponent('adIcon').clear()
            he.pool.putElement('adIcon', this.bottom_right.children[0])
        }


    },
    topSet(config) {
        if (config.isOpen) {
            let pre = he.pool.getElement('scrollAd')
            pre.parent = this.top_node
            pre.getComponent('scrollAd').init(config.creatives)
        }
    },
    bottomSet(config) {
        if (config.isOpen) {
            let pre = he.pool.getElement('adIcon')
            let pre2 = he.pool.getElement('adIcon')

            pre.position = cc.Vec2.ZERO
            pre.parent = this.bottom_left
            pre.opacity = 255
            let spt = pre.getComponent('adIcon')
            spt.init(config.creatives[0], true, true, 0.8)
            if (config.creatives[1]) {
                pre2.position = cc.Vec2.ZERO
                pre2.parent = this.bottom_right
                pre2.opacity = 255
                let spt2 = pre2.getComponent('adIcon')
                spt2.init(config.creatives[1], true, true, 0.8)
            } else {
                console.log(config)
            }
        }
    },

    startGameServer() {
        if (this.go_status) {
            return
        } else {
            this.go_status = true
        }
        he.voice.playEffect("button", "voice")
        let team = he.local.getJson('team', 'user')
        let isHaveInFight = false
        for (let i = 0; i < team.length; i++) {
            if (team[i].order >= 1) {
                isHaveInFight = true
                break
            }
        }
        if (!isHaveInFight) {
            gg.uiManager.addTip('请至少出战一个英雄')
            this.go_status = false
            return
        }
        gg.data.pass_id = this.pass
        // gg.data.goPass(this.pass)
        this.guideCheck()
        he.local.click(this.pass + '_pass')
        switch (common.sdk_env) {
            case Sdk_Platform.WECHAT:
                // let guideList = he.local.getJson('guideList', 'user')
                // if (!guideList[5]) {
                //     gg.uiManager.addPage(UI_Layer.Cover, {
                //         name: "gogoMiniForce",
                //         cover: true
                //     })
                // }
                gg.uiManager.addPage(UI_Layer.Cover, {
                    name: "trialNewRolePage",
                    cover: true
                })
                break
            default:
                gg.data.goPass(this.pass)
                gg.uiManager.addPage(UI_Layer.Cover, {
                    name: "gogoMiniForce",
                    cover: true
                })
                break
        }

    },
    //新手引导检查
    guideCheck() {
        let guideList = he.local.getJson('guideList', 'user')
        if (guideList) {
            if (!guideList[4] && gg.data.pass_id == 10101) {
                guideList[4] = 1
            }
            he.local.setJson('guideList', guideList, 'user')
        }

    },

    pageInit(pass) {
        if (pass) {
            this.pass = pass
            let passinfo = he.db.getDataByArgs('Pass', { id: this.pass })
            this.title_lab.string = `${passinfo.name}`
            this.updatePassReward(pass)
        } else {
            this.updatePassReward()
        }
        this.updateStar()
    },

    //箱子按钮
    gachaServer() {

        if (!this.gacha_bool && this.canClick) {
            // console.log("抽奖按钮被点击")
            this.canClick = false
            let time = parseInt(new Date().getTime()) + parseInt(this.dida)
            this.gacha_time = time
            he.local.set('gacha_time', time)
            let gachare = he.local.getJson('getGachaRes')
            gachare[this.gachaIndex] = 1
            he.local.setJson('getGachaRes', gachare)
            // this.bgSkeleton.setAnimation(0, 'gashapon_op_box', false)
            this.playSpine('gashapon_op_box', false, this.playSpineSec.bind(this))
            // this.bgSkeleton.addAnimation(0, 'gashapon_op_box_end', false)

        }
    },

    playSpineSec() {
        // console.log("boxPage显示")
        gg.uiManager.addPage(UI_Layer.Cover, {
            name: 'boxPage',
            cover: true,
            boxId: parseInt(5000) + parseInt(GACHALEVEL[this.gachaIndex])
        })
    },


    playSpine(animName, loop, callback) {
        let spine = this.bgSkeleton
        let track = spine.setAnimation(0, animName, loop);
        if (track) {
            // 注册动画的结束回调
            spine.setCompleteListener((trackEntry, loopCount) => {
                let name = trackEntry.animation ? trackEntry.animation.name : '';
                if (name === animName && callback) {
                    this.canClick = true
                    callback(); // 动画结束后执行自己的逻辑
                }
            });
        }
    },

    boxServer() {
        gg.uiManager.addPage(UI_Layer.Cover, {
            name: 'boxPage',
            close: true
        })
    },

    updateStar() {
        if (this.pass) {
            let pass_list = he.local.getJson('pass_list', 'user')
            for (let i = 0; i < pass_list.length; i++) {
                if (pass_list[i].id == this.pass) {
                    this.starInit(pass_list[i].star)
                }
            }
        }
    },

    starInit(num) {
        for (let i = 0; i < this.starNode.children.length; i++) {
            this.starNode.children[i].active = false
        }
        for (let j = 0; j < num; j++) {
            this.starNode.children[j].active = true
        }
    },
    boxsInit() {
        // for (let j = (this.boxContent.children.length); j > 0; j--) {
        //     he.pool.putElement('boxItem', this.boxContent.children[j - 1])
        // }
        let gachares = he.local.getJson('getGachaRes')
        this.gachaIndex = -1
        if (gachares && gachares.length > 0) {
            for (let j = 0; j < gachares.length; j++) {
                if (gachares[j] === 0) {
                    this.gachaIndex = j
                    break
                }
            }
            //15个已经全部走了一遍
            if (this.gachaIndex == -1) {
                gachares = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                he.local.setJson('getGachaRes', gachares)
                this.gachaIndex = 0
            }
        } else {
            gachares = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
            he.local.setJson('getGachaRes', gachares)
            this.gachaIndex = 0
        }
        for (let i = 0; i < 15; i++) {
            // let pre = he.pool.getElement('boxItem')
            // pre.parent = this.boxContent
            let spt = this.boxContent.children[i].getComponent('boxItem')
            if (i == this.gachaIndex || i == (this.gachaIndex + 1)) {
                spt.init(i, gachares[i], true)
            } else {
                spt.init(i, gachares[i], false)
            }
        }
        this.timeChangeLab = this.boxContent.children[this.gachaIndex].getChildByName('time').getComponent(cc.Label)
    },

    updatePassReward(pass) {
        let passInfo = null
        if (pass) {
            passInfo = he.db.getDataByArgs("Pass", { id: pass })
        } else {
            passInfo = he.db.getDataByArgs("Pass", { id: gg.data.pass_id })
        }
        let reward_list = passInfo.reward.split("#")
        for (let j = 0; j < this.content.children.length; j++) {
            this.content.children[j].active = false
        }
        for (let i = 0; i < reward_list.length; i++) {
            let reward_param = reward_list[i].split('_')
            this.content.children[i].active = true
            let itemScript = this.content.children[i].getComponent('bagItem')
            let item_id = parseInt(reward_param[0])
            itemScript.initInfo(item_id)
            this.content.children[i].getChildByName('background').active = false
        }
    },

    updateChargeStatus() {
        this.boxsInit()
        this.gacha_time = parseInt(he.local.get('gacha_time'))
        if (this.gacha_time == 'NaN') {
            this.gacha_time = +0
            he.local.set('gacha_time', this.gacha_time)
        }
        this.cantClick.active = true
        if (this.gacha_time > 0) {
            let nowDate = parseInt(new Date().getTime()) + parseInt(this.dida)
            let time = parseInt(nowDate) - parseInt(this.gacha_time)
            if (time > 0 && time < GACHATIMEGRP[this.gachaIndex] * 1000 * 60) {
                if (!this.gacha_bool) {
                    this.gacha_bool = true
                    this.schedule(this.updateChargeTime, 1);
                }
            }
        }
        this.bgSkeleton.setAnimation(0, 'stand_by', true)
        this.updateChargeTime()
    },
    // 更新充能时间
    updateChargeTime() {
        let nowDate = parseInt(new Date().getTime()) + parseInt(this.dida)
        let time = nowDate - this.gacha_time
        if (time > 0 && time < GACHATIMEGRP[this.gachaIndex] * 1000 * 60) {

            this.cantClick.active = false
            // this.frame_sp.fillRange = time / (GACHATIMEGRP[this.gachaIndex] * 1000 * 60)
            this.time_lab.node.active = true
            let nowTime = util.sceTostrSec(parseInt((GACHATIMEGRP[this.gachaIndex] * 1000 * 60 - time) / 1000))
            this.time_lab.string = nowTime
            this.timeChangeLab.string = nowTime
            this.gacha_btn.interactable = false
        } else {
            this.frame_sp.fillRange = 1
            this.cantClick.active = false
            // this.bgSkeleton.setAnimation(0, 'gashapon_op_box', false)
            this.bgSkeleton.defaultSkin = `box_${GACHALEVEL[this.gachaIndex]}`
            this.bgSkeleton.setSkin(`box_${GACHALEVEL[this.gachaIndex]}`)
            this.bgSkeleton.setAnimation(0, 'gashapon', false)
            this.bgSkeleton.addAnimation(0, 'gashapon_box', true)
            this.realBigBgSpine.setAnimation(0, 'gashapon', false)
            this.realBigBgSpine.addAnimation(0, 'stand_by', true)
            this.time_lab.node.active = false
            this.boxContent.children[this.gachaIndex].getChildByName('box_bg').color = cc.Color.BLUE
            this.timeChangeLab.node.active = false
            this.gacha_btn.interactable = true
            this.gacha_bool = false
            this.unschedule(this.updateChargeTime);
        }
    },
});
